package com.hefan.notify.listener;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.tiger.util.GlobalConstants;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.common.oss.OssImageService;
import com.hefan.common.util.DynamicProperties;
import com.hefan.live.bean.LiveLog;
import com.hefan.live.itf.LiveLogService;

@Component
public class ReceiveImCclistener implements GLLMessageListener {

	@Resource
	LiveLogService liveLogService;
	@Resource
	OssImageService ossImageService;

	Logger logger = LoggerFactory.getLogger(ReceiveImCclistener.class);

	@Override
	public TopicRegistry getTopicRegistry() {
		// TODO Auto-generated method stub
		return TopicRegistry.HEFANTV_IMCC;
	}


	@Override
	public TopicRegistryDev getTopicRegistryDev() {
		return TopicRegistryDev.HEFANTV_IMCC_DEV;
	}

	@Override
	public TopicRegistryTest getTopicRegistryTest() {
		return TopicRegistryTest.HEFANTV_IMCC_TEST;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Action consume(Message message, ConsumeContext context) {
		// TODO Auto-generated method stub
		String realTopic = message.getTag();
		logger.info("topic: {}, realTopic : {}, msg_id , msg_body: {} , tag : {}", message.getTopic(), realTopic, "im抄送开始",message.getTag());
		try {
			Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
			String imCcStr = (String) map.get("imCc");
			if(StringUtils.isBlank(imCcStr) || !JSON.parseObject(imCcStr).containsKey("eventType")){
				// 发送串关键词不存在丢弃
				return Action.CommitMessage;
			}
			String eventType = JSON.parseObject(imCcStr).getString("eventType");
			if (!eventType.equals("4")) {
				// 不是聊天室广播消息丢弃
				return Action.CommitMessage;
			}
			// 是否重发
			if(JSON.parseObject(imCcStr).containsKey("resendFlag")){
				String resendFlag = JSON.parseObject(imCcStr).getString("resendFlag");
				if (StringUtils.isNotBlank(resendFlag) && resendFlag.equals("1")) {
					// 重发丢弃
					return Action.CommitMessage;
				}
			}
			// 生成文件所在文件夹绝对路径
			// 获取roomId
			String roomId = JSON.parseObject(imCcStr).getString("roomId");
			if (StringUtils.isBlank(roomId)) {
				// roomId为空丢弃
				return Action.CommitMessage;
			}
			// 时间
			String msgTimestamp = JSON.parseObject(imCcStr).getString("msgTimestamp");
			// 获取liveUuid
			String liveTime = stampToDate(msgTimestamp, "yyyy-MM-dd HH:mm:ss");
			logger.info("roomId=" + roomId + "  liveTime=" + liveTime);
			LiveLog live = liveLogService.getLiveLogByLiveTime(roomId, liveTime);
			if (live == null || StringUtils.isBlank(live.getLiveUuid())) {
				// liveUuid为空丢弃
				return Action.CommitMessage;
			}
			// 生成文件绝对路径
			String time = stampToDate(msgTimestamp, "yyyyMMddHHmm");
			String filePath = roomId + "/" + live.getLiveUuid() + "/" + time + ".txt";
			ossImageService.appendObjectToOSS(GlobalConstants.PIC_OSS_BUCKET, filePath, imCcStr + "\r\n");
			logger.info("ReceiveImCclistener write ok!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
			// 失败丢弃
			return Action.CommitMessage;
		}
		logger.info("ReceiveImCclistener complete!");
		return Action.CommitMessage;
	}

	/**
	 * 创建文件夹
	 * 
	 * @Title: makeDirs
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param filePath
	 * @return
	 * @return: boolean
	 * @author: LiTeng
	 * @throws @date:
	 *             2016年10月11日 下午1:07:51
	 */
	public static boolean makeDirs(String folderPath) {
		if (folderPath == null || folderPath.isEmpty()) {
			return false;
		}
		File folder = new File(folderPath);
		return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
	}

	/*
	 * 将时间戳转换为时间
	 */
	public static String stampToDate(String s, String format) {
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		long lt = new Long(s);
		Date date = new Date(lt);
		res = simpleDateFormat.format(date);
		return res;
	}
}
